package org.example2;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.stream.Stream;

public class NestedJarReaderByJarFile {
    /**
     * https://blog.csdn.net/mmake1994/article/details/142524929
     */
    public static void main(String args[]) throws Exception {
        String jarPath = System.getProperty("user.dir") + "/jarFileRear/jarFileDir/nestedJar.jar";
        // 方案二：JarFile
        processJar(jarPath);
    }

    private static void processJar(String jarPath) {
        try (JarFile jarFile = new JarFile(new File(jarPath))) {
            System.out.println("jarFile:" + jarFile);

            Stream<JarEntry> parallel = jarFile.stream().parallel();

            // 过滤出所有符合要求的jar包
            parallel.filter(entry -> !entry.isDirectory() && entry.getName().startsWith("org/example/") && entry.getName().endsWith(".jar"))
                    .forEach(entry -> processNestedJar(jarFile, entry.getName()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void processNestedJar(JarFile jarFile, String entryName) {
        System.out.println("jarFile:" + jarFile.toString());
        System.out.println("processNestedJar:" + entryName);
        // 处理嵌套jar文件
        try (InputStream nestedJarStream = jarFile.getInputStream(jarFile.getJarEntry(entryName));


             JarInputStream jarInputStream = new JarInputStream(nestedJarStream)) {


            JarEntry nestedEntry;
            while ((nestedEntry = jarInputStream.getNextJarEntry()) != null) {

                System.out.println("nestedEntry:" + nestedEntry.getName());

                if (nestedEntry.isDirectory()) {
                    continue;
                }
                String nestedEntryName = nestedEntry.getName();
                if (!nestedEntryName.endsWith(".class")) {
                    continue;
                }
                try {
                    String className = nestedEntryName.replace('/', '.').replace(".class", "");
                    System.out.println("className:" + className);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

                System.out.println("--------------------------------------");
            }


        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
